package com.bupt.cad.controller;


import org.springframework.stereotype.Controller;
import org.springframework.util.ClassUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;
@Controller
public class FileUploadController {

    @ResponseBody
    @PostMapping("/upload")
    public String upload(@RequestParam("picture")MultipartFile uploadFile, HttpServletRequest request){
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd/");
        String path = "/home/luo/images/";
//        String path = ClassUtils.getDefaultClassLoader().getResource("").getPath();
        System.out.println(path);
//        String realPath = request.getSession().getServletContext().getRealPath("/uploadFile/");
        String format = dateFormat.format(new Date());
        File folder = new File(path+"uploadFile/"+format);
        if(!folder.exists()){
            folder.mkdirs();
        }
        String oldName = uploadFile.getOriginalFilename();
        String newName = UUID.randomUUID().toString()+oldName.substring(oldName.lastIndexOf("."),
                oldName.length());
        try {
//            uploadFi
            System.out.println(folder);
            uploadFile.transferTo(new File(folder,newName));
            String filePath = request.getScheme()+"://"+request.getServerName()+":"+
                    request.getServerPort()+"/uploadFile/"+format+newName;
            return filePath;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "上传失败";
    }
}
